import openai
from openai import OpenAI
import numpy as np
import json
import os
file_path = os.path.abspath(__file__)
dir_path = os.path.dirname(file_path)


def query(chat_log):
    """
    chat_log: 从formatted_data中获取的一条记录
    {
        "session_id": "00029c51f92e8f34250d6af329c9a8df",
        "user_id": "USERID_10003667",
        "content": "user:\txxxx\nwaiter:\txxxx\n"
    }
    """
    session_id = chat_log["session_id"]
    user_id = chat_log["user_id"]
    content = chat_log["content"]
    user_content = """You are a professional conversation analyst who is responsible for summarizing and analyzing the chat logs between users and customer service. Please generate a detailed analysis document based on the following conversation transcripts, with highlights including:\nTopic and purpose of the conversation:\nWhat is the main content of the exchange between the user and the customer service?\nWhat are the questions or needs raised by the user?\nUser sentiment analysis:\nThe emotions or attitudes (e.g., satisfaction, dissatisfaction, doubt, nervousness, etc.) displayed by the user during the conversation.\nQuality of customer service response:\nDid the customer service effectively solve the user's problem? If not, was there any follow-up?\nIs the tone and attitude of customer service friendly and professional?\nKey issues and solutions:\nThe specific issues raised by the user and the solutions given by the customer service.\nIf there are unresolved issues, please clearly point them out.\nThe overall atmosphere and conclusion of the dialog:\nWas the overall emotional disposition of the conversation positive, negative or neutral?\nAre there any areas for improvement, e.g. customer service response time, clarity of information, etc.?\nYou should reply in Chinese"""
    user_content += f"'''{content}'''"

    client = OpenAI(
        api_key="sk-81bf128c90424cd5bec2c9a3c54ef309",
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    messages = [
        {
            "role": "system",
            "content": "you are a helpful and precise assistant for summarizing Chat log",
        },
        {
            "role": "user",
            "content": user_content,
        },
        {
            "role": "assistant",
            "content": "",
        },
    ]

    response = client.chat.completions.create(
        model="qwen-max",  # 指定使用的模型名称
        messages=messages,  # 定义的消息列表
        max_tokens=1024,  # 限制最大令牌数为150
        response_format={
            "type": "text",  # 响应类型为纯文本
        }
    )
    ret = response.choices[0].message.content
    return ret

if __name__ == "__main__":
    data_dir = os.path.join(dir_path, "../Data/JD_chat.json")
    with open(data_dir, "r", encoding="utf-8") as f:
        docs = json.load(f)[1: ]
    
    total_files = len(docs)

    np.random.seed(123)
    idx = np.random.randint(total_files)
    chat_log = docs[idx]

    ret = query(chat_log)
    with open(os.path.join(dir_path, "../output/chatgptprompt_based_summarize_01.txt"), "w", encoding="utf-8") as f:
        f.write(chat_log["content"])
        f.write("\n")
        f.write("\n")
        f.write("\n")
        f.write("\n")
        f.write("\n")
        f.write("*"*100)
        f.write("\n")
        f.write(ret)